package com.example.webdemo.service;

//顾客信息控制组件

import com.example.webdemo.bean.customer;
import com.example.webdemo.dao.CustomerDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CustomerService {

    private final CustomerDao customerDao;
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public CustomerService(CustomerDao customerDao, JdbcTemplate jdbcTemplate) {
        this.customerDao = customerDao;
        this.jdbcTemplate = jdbcTemplate;
    }

    public customer createCustomer(customer customer) {
        int affectedRows = customerDao.insert(customer);
        if (affectedRows > 0) {
            return customerDao.findById(customer.getCust_id());
        }
        return null;
    }

    public customer updateCustomer(int id, customer customer) {
        int affectedRows = customerDao.update(customer);
        if (affectedRows > 0) {
            return customerDao.findById(customer.getCust_id());
        }
        return null;
    }

    public boolean deleteCustomer(int cust_id) {
        return customerDao.delete(cust_id) > 0;
    }

    public customer getCustomerById(int custId) {
        return customerDao.findById(custId);
    }

    public List<customer> getAllCustomers() {
        return customerDao.findAll();
    }

    public List<customer> searchCustomers(String custName, String custType, String custSource) {
        return customerDao.findByCondition(custName, custType, custSource);
    }

    public long countCustomers() {
        String sql = "SELECT COUNT(*) FROM customer";
        return jdbcTemplate.queryForObject(sql, Long.class);
    }
}